package com.yzc.android.ui.base.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

import butterknife.Bind;
import cn.pedant.SweetAlert.SweetAlertDialog;
import com.baoyz.actionsheet.ActionSheet;
import com.baoyz.actionsheet.ActionSheet.ActionSheetListener;
import com.skybeacon.sdk.ConfigCallback;
import com.skybeacon.sdk.ConnectionStateCallback;
import com.skybeacon.sdk.config.SKYBeaconCommunication;
import com.skybeacon.sdk.config.SKYBeaconConfig;
import com.skybeacon.sdk.config.SKYBeaconConfigException;
import com.skybeacon.sdk.config.SKYBeaconPower;
import com.skybeacon.sdk.locate.SKYBeacon;
import com.skybeacon.sdk.locate.SKYBeaconMultiIDs;
import com.yzc.android.R;
import com.yzc.android.beans.BeaconBean;
import com.yzc.android.event.BeaconScanEvent;
import com.yzc.android.event.EventBusManager;
import com.yzc.android.event.EventLifeCycleHandler;
import com.yzc.android.manager.ibeacon.IBeaconScanManager;
import com.yzc.android.manager.sensor.SensorConstant;
import com.yzc.android.utils.AppUtils;
import com.yzc.android.utils.LogUtils;
import com.yzc.android.utils.PreferencesUtils;
import com.yzc.android.utils.ThreadUtils;

/**
 * Created by yzc on 16/5/21.
 */
public class SensorSettingFragment extends NavBarBaseFragment implements ActionSheetListener {
    @Bind(R.id.et_sensor_accelerometer)
    EditText mSensorAccelerometer;

    @Bind(R.id.et_sensor_angle)
    EditText mSensorAngle;

    @Bind(R.id.et_ibeacon_name)
    EditText mEtIbeaconName;

    @Bind(R.id.et_ibeacon_uuid)
    EditText mEtIbeaconUuid;

    @Bind(R.id.et_ibeacon_major)
    EditText mEtIbeaconMajor;

    @Bind(R.id.et_ibeacon_minor)
    EditText mEtIbeaconMinor;

    @Bind(R.id.et_ibeacon_send_power)
    EditText mEtIbeaconSendPower;

    @Bind(R.id.et_ibeacon_measure_power)
    EditText mEtIbeaconMeasurePower;

    @Bind(R.id.et_ibeacon_broadcast_interval)
    EditText mEtIbeaconBroadcastInterval;

    @Bind(R.id.sv_main)
    ScrollView mSvMain;

    @Bind(R.id.tv_loading_status)
    TextView mTvLoadingStatus;

    private EventLifeCycleHandler mEventHandler;

    private SKYBeaconCommunication skyBeaconCommunication;

    private BeaconBean mBeacon;

    private int[] mSendPowerArray = {0, -21};

    private final static String ALIVE_SERVICE_TAG = "alive_service";


    @Override
    public int getLayout() {
        return R.layout.layout_fragment_sensor_setting;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        setHeaderTitle("阈值设置");

        mSensorAccelerometer.setText("" + SensorConstant.kAccelerationThreshold);
        mSensorAngle.setText("" + SensorConstant.kYawThreshold);
        mSensorAccelerometer.requestFocus();
        mSensorAccelerometer.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    // Perform action on key press
                    AppUtils.hideKeyboard(getContext());
                    return true;
                }
                return false;
            }
        });

        mSensorAngle.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    // Perform action on key press
                    AppUtils.hideKeyboard(getContext());
                    return true;
                }
                return false;
            }
        });

        mNavigationBar.setRightOnClickListener(new OnClickListener() {
            @Override
            public void onClick(final View v) {
                AppUtils.hideKeyboard(getContext());
                confirmConfigBeacon(getBeaconConfig());
            }
        });

        mTvLoadingStatus.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(final View v) {
                connectBeacon();
            }
        });

        mEtIbeaconSendPower.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(final View v) {
                String[] powerArray = new String[mSendPowerArray.length];
                for (int i = 0; i < mSendPowerArray.length; i++) {
                    powerArray[i] = ""+mSendPowerArray[i];
                }
                ActionSheet.createBuilder(getContext(), getFragmentManager())
                        .setCancelButtonTitle("取消")
                        .setOtherButtonTitles(powerArray)
                        .setCancelableOnTouchOutside(true)
                        .setListener(SensorSettingFragment.this).show();
            }
        });

        mEventHandler = new EventLifeCycleHandler() {
            public void onEvent(final BeaconScanEvent event) {
                BeaconBean beaconBean = event.getData();
                if (beaconBean != null) {
                    boolean changed = !beaconBean.proximityUuid.equals(
                            mBeacon.proximityUuid) || beaconBean.major != mBeacon.major || beaconBean.minor != mBeacon.minor;
                    if (changed) {
                        mBeacon = beaconBean;
                        connectBeacon();
                    }
                }
                else {
                    mNavigationBar.showRightView(false);
                    mTvLoadingStatus.setText("失去连接，稍后点击重试");
                    mTvLoadingStatus.setClickable(true);
                }
            }
        };

        return view;
    }

    @Override
    public void onEnter(final Object data) {
        LogUtils.d(ALIVE_SERVICE_TAG, "onEnter");
        super.onEnter(data);
        mBeacon = (BeaconBean)data;
    }

    @Override
    public void onBack() {
        super.onBack();
        EventBusManager.bindContainerAndHandler(this, mEventHandler).tryToRegisterIfNot();
        if (mBeacon != null) {
            LogUtils.d(ALIVE_SERVICE_TAG, "onEnter mac=%s", mBeacon.bluetoothAddress);
            updateViewByBeaconBean(mBeacon);
            connectBeacon();
        }
    }

    public SKYBeaconConfig getBeaconConfig() {
        SKYBeaconConfig skyBeaconConfig1 = new SKYBeaconConfig();
        if (!mEtIbeaconUuid.getText().toString().equals("")) {
            skyBeaconConfig1.setProximityUUID(mEtIbeaconUuid.getText().toString());
        }
        if (!mEtIbeaconMajor.getText().toString().equals("")) {
            skyBeaconConfig1.setMajor(Integer.valueOf(mEtIbeaconMajor.getText()
                                                              .toString()));
        }
        if (!mEtIbeaconMinor.getText().toString().equals("")) {
            skyBeaconConfig1.setMinor(Integer.valueOf(mEtIbeaconMinor.getText()
                                                              .toString()));
        }
        if (!mEtIbeaconMeasurePower.getText().toString().equals("")) {
            skyBeaconConfig1.setMeasuredPower(Integer.valueOf(mEtIbeaconMeasurePower
                                                                      .getText().toString()));
        }
        if (!mEtIbeaconSendPower.getText().toString().equals("")) {
            skyBeaconConfig1.setTxpower(SKYBeaconPower.getPower(Integer
                                                                        .valueOf(mEtIbeaconSendPower.getText().toString())));
        }
        if (!mEtIbeaconBroadcastInterval.getText().toString().equals("")) {
            skyBeaconConfig1.setIntervalMillisecond(Integer.valueOf(mEtIbeaconBroadcastInterval.getText().toString()));
        }
        if (!mEtIbeaconName.getText().toString().equals("")) {
            skyBeaconConfig1.setDeviceName(mEtIbeaconName.getText().toString());
        }

        return skyBeaconConfig1;
    }


    public void connectBeacon() {
        final SweetAlertDialog loadingDialog = new SweetAlertDialog(getContext(), SweetAlertDialog.PROGRESS_TYPE);
        loadingDialog.setTitleText("正在连接");
        loadingDialog.setCancelable(false);
        ConnectionStateCallback connectionStateCallback = new ConnectionStateCallback() {
            @Override
            public void onDisconnected() {
                // TODO Auto-generated method stub
                ThreadUtils.runOnMainThreadSync(new Runnable() {
                    @Override
                    public void run() {
                        loadingDialog.dismiss();
                        new SweetAlertDialog(getActivity(), SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("提示")
                                .setContentText("连接断开")
                                .setConfirmText("确定").show();
                        mTvLoadingStatus.setText("连接失败，点击此处重试");
                        mTvLoadingStatus.setClickable(true);
                    }
                });
            }

            @Override
            public void onConnectedSuccess(SKYBeaconMultiIDs skyBeaconMultiIDs) {
                // final SKYBeaconMultiIDs skyBeaconMultiIDsTmp =
                // skyBeaconMultiIDs;
                ThreadUtils.runOnMainThreadSync(new Runnable() {
                    @Override
                    public void run() {
                        loadingDialog.setTitleText("提示")
                                .setContentText("连接成功,multiBeacon")
                                .changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
                        mTvLoadingStatus.setText("连接成功");
                        mTvLoadingStatus.setClickable(false);
                    }
                });
            }

            @Override
            public void onConnectedSuccess(final SKYBeacon skyBeacon) {
                // TODO Auto-generated method stub
                ThreadUtils.runOnMainThreadSync(new Runnable() {
                    @Override
                    public void run() {
                        loadingDialog.setTitleText("提示")
                                .setContentText("连接成功,singleBeacon")
                                .changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
                        updateViewBySKYBeaconBean(skyBeacon);
                        mNavigationBar.showRightView(true);
                        mTvLoadingStatus.setText("连接成功");
                        mTvLoadingStatus.setClickable(false);
                    }
                });
            }

            @Override
            public void onConnectedFailed(
                    SKYBeaconConfigException skyBeaconConfigException) {
                // TODO Auto-generated method stub
                final String exceptionInfo = skyBeaconConfigException
                        .getMessage()
                        + String.valueOf(skyBeaconConfigException.getCode());

                ThreadUtils.runOnMainThreadSync(new Runnable() {
                    @Override
                    public void run() {
                        loadingDialog.setTitleText("异常")
                                .setContentText(exceptionInfo)
                                .setConfirmText("确定")
                                .changeAlertType(SweetAlertDialog.ERROR_TYPE);
                        mTvLoadingStatus.setText("连接失败，点击此处重试");
                        mTvLoadingStatus.setClickable(true);
                    }
                });
            }
        };
        if (mBeacon != null) {
            skyBeaconCommunication = new SKYBeaconCommunication(getContext());
            SKYBeacon skyBeaconConnect = new SKYBeacon(mBeacon.bluetoothAddress);
            skyBeaconCommunication.connect(skyBeaconConnect, connectionStateCallback);
            loadingDialog.show();
            mTvLoadingStatus.setText("正在连接，请稍后");
            mTvLoadingStatus.setClickable(false);
            mNavigationBar.showRightView(false);
        }
    }

    private void confirmConfigBeacon(final SKYBeaconConfig config) {
        final SweetAlertDialog loadingDialog = new SweetAlertDialog(getContext(), SweetAlertDialog.PROGRESS_TYPE);
        loadingDialog.setTitleText("请稍后");
        loadingDialog.setCancelable(false);
        loadingDialog.show();
        skyBeaconCommunication.configSKYBeacon(config,
                                               new ConfigCallback() {

                                                   @Override
                                                   public void onConfigSuccess() {
                                                       // TODO Auto-generated method stub
                                                       ThreadUtils.runOnMainThreadSync(new Runnable() {
                                                           @Override
                                                           public void run() {
                                                               loadingDialog.setTitleText("提示")
                                                                       .setContentText("配置成功")
                                                                       .changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
                                                               SensorConstant.kAccelerationThreshold = Double.valueOf(mSensorAccelerometer.getText().toString());
                                                               SensorConstant.kYawThreshold = Double.valueOf(mSensorAngle.getText().toString());
                                                               boolean changed = !config.getProximityUUID().equals(mBeacon.proximityUuid)
                                                                       || config.getMajor() != mBeacon.major
                                                                       || config.getMinor() != mBeacon.minor;
                                                               if (changed) {
                                                                   PreferencesUtils.putString(getContext(),
                                                                                              IBeaconScanManager.PRE_KEY_IBEACON_UUID,
                                                                                              config.getProximityUUID());
                                                                   PreferencesUtils.putInt(getContext(),
                                                                                           IBeaconScanManager
                                                                                                   .PRE_KEY_IBEACON_MAJOR,
                                                                                           config.getMajor());
                                                                   PreferencesUtils.putInt(getContext(),
                                                                                           IBeaconScanManager.PRE_KEY_IBEACON_MINOR,
                                                                                           config.getMinor());
                                                               }
                                                           }
                                                       });
                                                   }

                                                   @Override
                                                   public void onConfigFailed(
                                                           SKYBeaconConfigException skyBeaconConfigException) {
                                                       final String exceptionInfo = skyBeaconConfigException
                                                               .getMessage()
                                                               + String.valueOf(skyBeaconConfigException
                                                                                        .getCode());
                                                       // TODO Auto-generated method stub
                                                       ThreadUtils.runOnMainThreadSync(new Runnable() {
                                                           @Override
                                                           public void run() {
                                                               loadingDialog.setTitleText("异常")
                                                                       .setContentText(exceptionInfo)
                                                                       .setConfirmText("确定")
                                                                       .changeAlertType(SweetAlertDialog.ERROR_TYPE);
                                                           }
                                                       });
                                                   }
                                               });
    }

    void updateViewBySKYBeaconBean(SKYBeacon beacon) {
        mEtIbeaconName.setText(beacon.getDeviceName());
        mEtIbeaconUuid.setText(beacon.getProximityUUID());
        mEtIbeaconMajor.setText(""+beacon.getMajor());
        mEtIbeaconMajor.setHint(""+beacon.getFirmwareVersionMajor());
        mEtIbeaconMinor.setText(""+beacon.getMinor());
        mEtIbeaconMinor.setHint(""+beacon.getFirmwareVersionMinor());
        mEtIbeaconSendPower.setText(beacon.getTxpower().toString());
        mEtIbeaconBroadcastInterval.setText(""+beacon.getIntervalMillisecond());
        mEtIbeaconMeasurePower.setText(""+beacon.getMeasuredPower());
    }

    void updateViewByBeaconBean(BeaconBean beacon) {
        mEtIbeaconUuid.setText(TextUtils.isEmpty(beacon.proximityUuid) ? "" : beacon.proximityUuid);
        mEtIbeaconMajor.setText(""+beacon.major);
        mEtIbeaconMinor.setText(""+beacon.minor);
    }

    @Override
    public void onOtherButtonClick(final ActionSheet actionSheet, final int index) {
        mEtIbeaconSendPower.setText(""+mSendPowerArray[index]);
    }

    @Override
    public void onDismiss(final ActionSheet actionSheet, final boolean isCancel) {

    }

    @Override
    public void pullToRefreshHandler() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (skyBeaconCommunication != null) {
            skyBeaconCommunication.disconnect();
        }
    }

    @Override
    protected boolean enableDefaultBack() {
        return true;
    }

    @Override
    protected void onBackPressed() {
        super.onBackPressed();
    }
}
